<?php

namespace business\elasticsearch\services;


use business\elasticsearch\models\BigDataCommencePermitModel;

class BigDataCommencePermitService
{
    public function getDataList(
        $keyword,
        $province=[],
        $city,
        $companyType,
        $areaLower,
        $areaUpper,
        $priceLower,
        $priceUpper,
        $beginLower,
        $beginUpper,
        $finishLower,
        $finishUpper,
        $page,
        $pageSize
    ) {
        $condition = $this->constructCondition(
            $keyword,
            $province,
            $city,
            $companyType,
            $areaLower,
            $areaUpper,
            $priceLower,
            $priceUpper,
            $beginLower,
            $beginUpper,
            $finishLower,
            $finishUpper
        );
        //var_dump(json_encode($condition));
        $query     = BigDataCommencePermitModel::find()
            ->query($condition);

        //高亮处理
        $highlight = [
            'pre_tags'  => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields"    => [
                "project_name" => new \stdClass(),
                "developer_name" => new \stdClass(),
                "construction_unit" => new \stdClass(),
            ]
        ];
        $query->highlight($highlight);
        $query->orderBy(['start_time' => SORT_DESC]);

        $total = $query->count();
        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $data = $query->asArray()->all();
        //数据处理
        $result = ['total' => $total, 'list' => []];
        foreach ($data as $dv) {
            $tmp                = $dv['_source'];
            $tmp['nameSuggest'] = $tmp['project_name'];
            if (!empty($dv['highlight'])) {
                foreach ($dv['highlight'] as $key => $value) {
                    $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                }
            }

            if (!array_key_exists('end_time', $tmp)) {
                $tmp['end_time'] = '';
            }

            $result['list'][] = $tmp;
        }
        return $result;
    }

    private function constructCondition(
        $keyword = '',
        $province = [],
        $city = '',
        $companyType = '',
        $areaLower,
        $areaUpper,
        $priceLower,
        $priceUpper,
        $beginLower,
        $beginUpper,
        $finishLower,
        $finishUpper
    ) {
        $query = [];
        $slop = !empty(\Yii::$app->params['CommonDataDeveloperSlop']) ?  \Yii::$app->params['CommonDataDeveloperSlop'] : 2;
        $must = [];
        $query['function_score']['query']['bool']['must'] = &$must;


        if (!empty($keyword)) {
            $should = [];
            $must[] = ['bool' => ['should' => &$should]];

            $companyBool = [];
            $companyBool[] = [
                'match_phrase' => ['developer_name' => ["query" => $keyword, "boost" => 3, 'slop' => $slop]]
            ];
            $should[] = ["bool" => ["must" => $companyBool]];

            $projectBool = [];
            $projectBool[] = [
                'match_phrase' => ['project_name' => ["query" => $keyword, "boost" => 3, 'slop' => $slop]]
            ];
            $should[] = ["bool" => ["must" => $projectBool]];

            $constructionBool = [];
            $constructionBool[] = [
                'match_phrase' => ['construction_unit' => ["query" => $keyword, "boost" => 3, 'slop' => $slop]]
            ];
            $should[] = ["bool" => ["must" => $constructionBool]];
        }

        // 省市
        if (!empty($province)) {
            $must[] = ["terms" => ['province_code' => $province]];
        }
        if (!empty($city)) {
            $must[] = ["term" => ['city_code' => $city]];
        }

        //企业类型
        if (!empty($companyType)) {
            $must[] = ["term" => ['company_type_label' => $companyType]];
        }

        // 面积
        $areaRange = [];
        if (!empty($areaLower)) {
            $areaRange['gte'] = $areaLower;
        }
        if (!empty($areaUpper)) {
            $areaRange['lt'] = $areaUpper;
        }
        if (!empty($areaRange)) {
            $must[] = ['range' => ['construction_area' => $areaRange]];
        }

        // 单价区间
        $priceRange = [];
        if (!empty($priceLower)) {
            $priceRange['gte'] = $priceLower;
        }
        if (!empty($priceUpper)) {
            $priceRange['lt'] = $priceUpper;
        }
        if (!empty($priceRange)) {
            $must[] = ['range' => ['contract_price' => $priceRange]];
        }

        // 开工日期区间
        $beginDateRange = [];
        if (!empty($beginLower)) {
            $beginDateRange['gte'] = date('Y-m-d', strtotime($beginLower));
        }
        if (!empty($beginUpper)) {
            $beginDateRange['lt'] = date('Y-m-d', strtotime($beginUpper));
        }
        if (!empty($beginDateRange)) {
            $must[] = ['range' => ['start_time' => $beginDateRange]];
        }

        // 竣工日期区间
        $finishDateRange = [];
        if (!empty($finishLower)) {
            $finishDateRange['gte'] = date('Y-m-d', strtotime($finishLower));
        }
        if (!empty($finishUpper)) {
            $finishDateRange['lt'] = date('Y-m-d', strtotime($finishUpper));
        }
        if (!empty($finishDateRange)) {
            $must[] = ['range' => ['completed_time' => $finishDateRange]];
        }

        return $query;
    }

    public function guessNames($keyword, $pageSize) {
        $page = 1;

        $query = [];
        if (!empty($keyword)) {
            $query['function_score']['query']['bool']['must'][] = [
                'match_phrase' => ['project_name' => $keyword]
            ];
        }

        $query     = BigDataCommencePermitModel::find()
            ->query($query);

        //高亮处理
        $highlight = [
            'pre_tags'  => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields"    => [
                "project_name" => new \stdClass(),
            ]
        ];
        $query->highlight($highlight);
        $query->orderBy(['_score' => SORT_DESC]);

        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $data = $query->asArray()->all();
        //数据处理
        $result = [];
        foreach ($data as $dv) {
            $item               = array();
            $tmp                = $dv['_source'];
            $tmp['nameSuggest'] = $tmp['project_name'];
            if (!empty($dv['highlight'])) {
                foreach ($dv['highlight'] as $key => $value) {
                    $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                }
            }
            $item['title']   = $tmp['project_name'];
            $item['titleHL'] = $tmp['project_nameHL'];
            $result[]                 = $item;
        }
        return $result;
    }
}
